package spring.angularjs.customhandler;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import spring.angularjs.domain.History;
import spring.angularjs.domain.Userinfo;
import spring.angularjs.services.Services;

/**
 * After login success. Save time login to table History. And redirect to home
 * page
 * 
 *
 */
@Component
public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler {

	@Autowired
	private Services services;

	public static int idHistory;

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse respone, Authentication arg2)
			throws IOException, ServletException {
		// get User login
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		String loginId = auth.getName();
		Userinfo user = services.getUserInfo(loginId);

		History history = new History(user, new Date());

		// get Id identity after add to table
		int id = services.addHistory(history);
		idHistory = id;

		// redirect to homepage
		if (user.getRole().getRolename().equals("ROLE_ADMIN")) {
			redirectStrategy.sendRedirect(request, respone, "/indexadmin");
		}
		if (user.getRole().getRolename().equals("ROLE_SUPPORT")) {
			redirectStrategy.sendRedirect(request, respone, "/indexsupport");
		}
		if (user.getRole().getRolename().equals("ROLE_USER")) {
			redirectStrategy.sendRedirect(request, respone, "/indexuser");
		}
	}
}
